from django.db import models
from django.db.models import get_model
from django.db import connection

import settings

class Tag(models.Model):
    name = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(unique=True)    
    #dynamically create M2M fields for this model
    for key, value in settings.TAGGABLE_MODELS.iteritems():
        codestring = ""+key+" = models.ManyToManyField('"+value+"', blank=True, null=True)"
        exec(codestring)
    
#    def createAssociationTables(self):
#        for key, value in settings.TAGGABLE_MODELS.iteritems():    
#            #create association tables for any relationships that don't already exist
#            try:
#                #check if table exists. If not, create it.
#                cursor = connection.cursor()
#                sql = "SELECT * from magictags_tag_users"
#                cursor.execute(sql)
#            except:
#                cursor = connection.cursor()
#                sql = """CREATE TABLE magictags_tag_users (
#                        id integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
#                        tag_id integer NOT NULL,
#                        user_id integer NOT NULL,
#                        UNIQUE(tag_id, user_id)
#                        );
#                        
#                        ALTER TABLE magictags_tag_users ADD CONSTRAINT magictags_tag_users_tag_fk FOREIGN KEY (tag_id) REFERENCES magictags_tag (id);
#                        ALTER TABLE magictags_tag_users ADD CONSTRAINT magictags_tag_users_users_fk FOREIGN KEY (user_id) REFERENCES auth_user (id);
#                """
#                cursor.execute(sql)
    
    def __unicode__(self):
        return self.name
    

#class TaggedItem(models.Model):
#    tag = models.ForeignKey('Tag')
#    content_type = models.ForeignKey(ContentType, related_name="content_type")
#    object_id = models.PositiveIntegerField()
#    content_object = generic.GenericForeignKey('content_type', 'object_id')
    
#TEST models
#class TestItem(models.Model):
#    name = models.CharField(max_length=100, blank=True)
#    tags = models.ManyToManyField('magictags.Tag', blank=True)
#    
#    def __unicode__(self):
#        return self.name
